package com.example.esredisrabbitmqdemo.controller;

import com.example.esredisrabbitmqdemo.conf.DelayQueueConfig;
import com.example.esredisrabbitmqdemo.conf.ExpirationMessagePostProcessor;
import com.rabbitmq.client.Channel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: es-redis-rabbitmq-demo
 * @BelongsPackage: com.example.esredisrabbitmqdemo.controller
 * @Author: 江岸
 * @CreateTime: 2020-07-07 19:42
 * @Description:
 */
@RestController
@Api(tags = "OrderController",description = "订单表现层")
public class OrderController {
    //模拟数据库订单状态
    static Map<String,String> map = new HashMap<>();

    @Autowired
    RabbitTemplate rabbitTemplate;


    private Logger logger = LoggerFactory.getLogger(OrderController.class);


    @ApiOperation(value = "添加订单")
    @PostMapping("addOrder")
    public Map<String,String> addOrder(){
        map.put("order","待支付");
        //发送延时队列
        rabbitTemplate.convertAndSend(DelayQueueConfig.DELAY_QUEUE_PER_QUEUE_TTL_NAME,
                (Object) ("msg:"+new Date()),
                new ExpirationMessagePostProcessor("5000"));
        return map;
    }

    @ApiOperation(value = "查询订单")
    @PostMapping("queryOrder")
    public Map<String,String> queryOrder(){
        return map;
    }

    //监听的是处理队列
    @RabbitListener(queuesToDeclare = @Queue(DelayQueueConfig.DELAY_PROCESS_QUEUE_NAME))
    public void process(Channel channel, String json, Message message){
        int i = (int) (Math.random()+0.5);
        try {
            int res = 100 / i;
            logger.info("处理消息于{} 消息：{}", new Date(),json);
            //改订单状态
            map.put("order","已支付");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            try {
                logger.info("消息确认消费者处理消息时发生异常：{}",new Date(),json);


                //抛弃此条消息
                //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
                //重新放入队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }finally {
        }
    }
}
